var CopyWebpackPlugin = require('copy-webpack-plugin');
var path = require('path');
var fs = require('fs');
const {
  appName,
  versionCode
} = require('@wecode/wlk-cli/lib/tools/lib/plugin');

const buildPath = path.resolve(
  __dirname,
  `./build/apps/${appName}/${versionCode}/`
);
const HtmlWebpackPlugin = require('html-webpack-plugin');

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const DEBUG = !process.argv.includes('prod') && !process.argv.includes('uat');
// console.log(DEBUG, '--- DEBUG ---');
// 判断是否是在当前生产环境
// const isProduction = process.argv.includes('prod');

// 获取所有入口文件
const entries = require('./entries.config.js');
const VueLoaderPlugin = require('vue-loader/lib/plugin');

const requireJSON = function(filePath) {
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
};
const babelrc = requireJSON('./.babelrc');

const babelOptions = Object.assign({}, babelrc, { cacheDirectory: true });

module.exports = {
  mode: DEBUG
    ? 'development'
    : process.argv.includes('uat')
      ? 'none'
      : 'production',
  // 插件项
  plugins: [
    // 把指定文件夹下的文件复制到指定的目录
    new CopyWebpackPlugin([
      {
        from: './src/assets',
        to: './assets',
        toType: 'dir'
      }
    ]),
    new MiniCssExtractPlugin({
      filename: 'css/[name].css?v=[hash]'
    }),
    new VueLoaderPlugin() // 误删 vue-loader 使用
  ],
  // 页面入口文件配置
  entry: entries,
  // 入口文件输出配置
  output: {
    path: buildPath,
    filename: 'js/[name].js',
    publicPath: '../',
    chunkFilename: 'js/[name].js?v=[hash]'
  },
  module: {
    // 加载器配置
    rules: [
      {
        test: /\.(css)$/,
        use: [
          !DEBUG ? MiniCssExtractPlugin.loader : 'style-loader',
          'css-loader',
          'postcss-loader'
        ]
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            ...babelOptions
          }
        }
      },
      // 我用的是less
      {
        test: /\.less$/,
        use: ['style-loader', 'css-loader', 'less-loader']
      },
      {
        test: /\.vue$/,
        use: ['vue-loader']
      },
      // {test: /\.scss$/, loader: 'style!css!sass?sourceMap'},
      {
        test: /\.(png|jpg|jpeg|gif|eot|ttf|woff|woff2|svg|svgz)(\?.+)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000
            }
          }
        ]
      }
    ]
  },
  devtool: DEBUG ? 'source-map' : false,
  optimization: {
    splitChunks: {
      chunks: 'all',
      minSize: 30000,
      maxSize: 0,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 5,
      automaticNameDelimiter: '~',
      name: 'hepler',
      cacheGroups: {
        vendor: {
          // 基础类库
          chunks: 'all',
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          priority: 10,
          enforce: true
        }
      }
    }
  },
  resolve: {
    // 误删
    extensions: ['.js', '.vue'],
    alias: {
      vue$: 'vue/dist/vue.common.js'
    }
  }
  // plugins: [
  //   // make sure to include the plugin for the magic
  //   new VueLoaderPlugin()
  // ],
};

// 生成HTML文件
const chunks = Object.keys(entries);
chunks.forEach(function(name) {
  if (name === 'vendor') {
    return;
  }
  const filename = entries[name]
    .substr(entries[name].lastIndexOf('/') + 1)
    .replace('.js', '.html');
  let filedirectory = entries[name]
    .substr(0, entries[name].lastIndexOf('/') + 1)
    .replace('./src/js', './src/html');
  filedirectory = filedirectory.replace('./src/', '');
  const filepath = path.join(filedirectory, filename);
  const conf = {
    title: name,
    filename: filepath,
    template: path.join('./src/', filepath),
    inject: 'body',
    hash: true,
    minify: {
      removeComments: true,
      collapseWhitespace: false
    }
  };
  if (name in module.exports.entry) {
    conf.chunks = ['vendor', name];
    conf.hash = false;
  }
  module.exports.plugins.push(new HtmlWebpackPlugin(conf));
});
